<template>
  <div class="activity-detail">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <el-button @click="goBack" circle>
          <el-icon><ArrowLeft /></el-icon>
        </el-button>
        <div class="title-section">
          <h1>活动详情</h1>
          <p>查看活动的详细信息和参与者列表</p>
        </div>
      </div>
      <div class="header-actions">
        <el-button type="primary" @click="editActivity">
          <el-icon><Edit /></el-icon>
          编辑活动
        </el-button>
        <el-button type="danger" @click="deleteActivity">
          <el-icon><Delete /></el-icon>
          删除活动
        </el-button>
      </div>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <el-skeleton :rows="8" animated />
    </div>

    <!-- 活动详情 -->
    <div v-else-if="activity" class="activity-content">
      <!-- 基本信息卡片 -->
      <el-row :gutter="20">
        <el-col :span="16">
          <el-card shadow="never" class="info-card">
            <template #header>
              <div class="card-header">
                <span class="card-title">基本信息</span>
                <el-tag :type="getStatusType(activity.status)" size="large">
                  {{ getStatusText(activity.status) }}
                </el-tag>
              </div>
            </template>

            <div class="activity-info">
              <div class="info-row">
                <label>活动标题：</label>
                <span class="value">{{ activity.title }}</span>
              </div>

              <div class="info-row">
                <label>活动描述：</label>
                <div class="value description">
                  {{ activity.description || '暂无描述' }}
                </div>
              </div>

              <div class="info-row">
                <label>活动类型：</label>
                <span class="value">
                  <el-tag>{{ getActivityTypeText(activity.activity_type) }}</el-tag>
                </span>
              </div>

              <div class="info-row" v-if="activity.tags && activity.tags.length">
                <label>活动标签：</label>
                <span class="value">
                  <el-tag v-for="tag in activity.tags" :key="tag" type="info" class="tag-item">
                    {{ tag }}
                  </el-tag>
                </span>
              </div>

              <div class="info-row">
                <label>开始时间：</label>
                <span class="value">
                  <el-icon><Clock /></el-icon>
                  {{ formatDateTime(activity.start_time) }}
                </span>
              </div>

              <div class="info-row">
                <label>结束时间：</label>
                <span class="value">
                  <el-icon><Clock /></el-icon>
                  {{ formatDateTime(activity.end_time) }}
                </span>
              </div>

              <div class="info-row" v-if="activity.registration_deadline">
                <label>报名截止：</label>
                <span class="value">
                  <el-icon><Clock /></el-icon>
                  {{ formatDateTime(activity.registration_deadline) }}
                </span>
              </div>

              <div class="info-row">
                <label>活动地点：</label>
                <span class="value">
                  <span v-if="activity.venue">
                    <el-icon><Location /></el-icon>
                    {{ activity.venue.name }}
                  </span>
                  <span v-else-if="activity.location_name">
                    <el-icon><Location /></el-icon>
                    {{ activity.location_name }}
                  </span>
                  <span v-else class="text-muted">未指定地点</span>
                </span>
              </div>

              <div class="info-row" v-if="activity.location_address">
                <label>详细地址：</label>
                <span class="value">{{ activity.location_address }}</span>
              </div>

              <div class="info-row">
                <label>费用信息：</label>
                <span class="value">
                  <el-tag v-if="activity.is_free" type="success">免费活动</el-tag>
                  <span v-else>
                    <el-tag type="warning">收费活动</el-tag>
                    <span class="fee">￥{{ activity.fee }}</span>
                  </span>
                </span>
              </div>

              <div class="info-row" v-if="!activity.is_free && activity.fee_description">
                <label>费用说明：</label>
                <span class="value">{{ activity.fee_description }}</span>
              </div>

              <div class="info-row" v-if="activity.requirements">
                <label>参与要求：</label>
                <div class="value">{{ activity.requirements }}</div>
              </div>

              <div class="info-row" v-if="activity.contact_info">
                <label>联系方式：</label>
                <div class="value">{{ activity.contact_info }}</div>
              </div>

              <div class="info-row" v-if="activity.notes">
                <label>备注信息：</label>
                <div class="value">{{ activity.notes }}</div>
              </div>

              <div class="info-row">
                <label>活动设置：</label>
                <div class="value">
                  <el-tag v-if="activity.need_approval" type="warning" class="setting-tag">需要审核</el-tag>
                  <el-tag v-if="activity.allow_waitlist" type="info" class="setting-tag">允许候补</el-tag>
                </div>
              </div>
            </div>
          </el-card>
        </el-col>

        <el-col :span="8">
          <!-- 组织者信息 -->
          <el-card shadow="never" class="organizer-card">
            <template #header>
              <span class="card-title">组织者信息</span>
            </template>
            
            <div v-if="activity.organizer" class="organizer-info">
              <div class="organizer-avatar">
                <el-avatar :size="60">
                  <el-icon><User /></el-icon>
                </el-avatar>
              </div>
              <div class="organizer-details">
                <h3>{{ activity.organizer.nickname }}</h3>
                <p><el-icon><Phone /></el-icon> {{ activity.organizer.phone }}</p>
                <p v-if="activity.organizer.email">
                  <el-icon><Message /></el-icon> {{ activity.organizer.email }}
                </p>
              </div>
            </div>
          </el-card>

          <!-- 参与统计 -->
          <el-card shadow="never" class="stats-card">
            <template #header>
              <span class="card-title">参与统计</span>
            </template>
            
            <div class="stats-content">
              <div class="stat-item">
                <div class="stat-number">{{ activity.participant_count || 0 }}</div>
                <div class="stat-label">当前参与人数</div>
              </div>
              <div class="stat-item">
                <div class="stat-number">{{ activity.max_participants }}</div>
                <div class="stat-label">最大参与人数</div>
              </div>
              <div class="stat-item">
                <div class="stat-number">{{ activity.min_participants }}</div>
                <div class="stat-label">最少参与人数</div>
              </div>
              <div class="stat-item">
                <div class="stat-number">{{ activity.view_count || 0 }}</div>
                <div class="stat-label">浏览次数</div>
              </div>
            </div>

            <!-- 参与进度 -->
            <div class="progress-section">
              <div class="progress-label">
                <span>参与进度</span>
                <span>{{ getParticipantPercentage() }}%</span>
              </div>
              <el-progress 
                :percentage="getParticipantPercentage()"
                :stroke-width="12"
                :status="getProgressStatus()"
              />
            </div>
          </el-card>

          <!-- 活动图片 -->
          <el-card v-if="activity.images && activity.images.length" shadow="never" class="images-card">
            <template #header>
              <span class="card-title">活动图片</span>
            </template>
            
            <div class="activity-images">
              <el-image
                v-for="(image, index) in activity.images"
                :key="index"
                :src="image"
                fit="cover"
                class="activity-image"
                :preview-src-list="activity.images"
                :initial-index="index"
              />
            </div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 参与者列表 -->
      <el-card shadow="never" class="participants-card">
        <template #header>
          <div class="card-header">
            <span class="card-title">参与者列表</span>
            <span class="participant-count">({{ participants.length }}人)</span>
          </div>
        </template>

        <el-table :data="participants" style="width: 100%">
          <el-table-column prop="user.nickname" label="用户昵称" width="200" />
          <el-table-column prop="user.phone" label="手机号" width="150" />
          <el-table-column label="性别" width="80">
            <template #default="{ row }">
              <span>{{ row.user.gender === 'male' ? '男' : row.user.gender === 'female' ? '女' : '未知' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="加入时间" width="180">
            <template #default="{ row }">
              {{ formatDateTime(row.joined_at) }}
            </template>
          </el-table-column>
          <el-table-column label="状态" width="100">
            <template #default="{ row }">
              <el-tag :type="row.status === 'joined' ? 'success' : 'info'">
                {{ row.status === 'joined' ? '已参与' : '已退出' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="150">
            <template #default="{ row }">
              <el-button link type="primary" @click="viewUserProfile(row.user)">
                查看详情
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <div v-if="!participants.length" class="empty-participants">
          <el-empty description="暂无参与者" />
        </div>
      </el-card>
    </div>

    <!-- 错误状态 -->
    <div v-else class="error-container">
      <el-result icon="error" title="获取活动详情失败" sub-title="请检查网络连接或稍后重试">
        <template #extra>
          <el-button type="primary" @click="fetchActivityDetail">重新加载</el-button>
          <el-button @click="goBack">返回列表</el-button>
        </template>
      </el-result>
    </div>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  ArrowLeft, Edit, Delete, Clock, Location, User, Phone, Message 
} from '@element-plus/icons-vue'
import request from '@/utils/request'
import { formatDateTime } from '@/utils/common'

export default {
  name: 'ActivityDetail',
  components: {
    ArrowLeft, Edit, Delete, Clock, Location, User, Phone, Message
  },
  setup() {
    const route = useRoute()
    const router = useRouter()
    
    const loading = ref(true)
    const activity = ref(null)
    const participants = ref([])

    // 获取活动详情
    const fetchActivityDetail = async () => {
      loading.value = true
      try {
        const activityId = route.params.id
        const response = await request.get(`/v1/admin/activities/${activityId}`)
        
        if (response.code === 200) {
          activity.value = response.data
          participants.value = response.data.participants || []
        } else {
          ElMessage.error('获取活动详情失败')
        }
      } catch (error) {
        console.error('获取活动详情失败:', error)
        ElMessage.error('获取活动详情失败')
      } finally {
        loading.value = false
      }
    }

    // 返回列表
    const goBack = () => {
      router.push('/activity/list')
    }

    // 编辑活动
    const editActivity = () => {
      // 这里可以跳转到编辑页面或打开编辑对话框
      ElMessage.info('编辑功能开发中...')
    }

    // 删除活动
    const deleteActivity = () => {
      ElMessageBox.confirm(
        `确定要删除活动 "${activity.value.title}" 吗？此操作不可恢复。`,
        '确认删除',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(async () => {
        try {
          await request.delete(`/v1/admin/activities/${activity.value.id}`)
          ElMessage.success('删除成功')
          router.push('/activity/list')
        } catch (error) {
          console.error('删除失败:', error)
          ElMessage.error('删除失败')
        }
      })
    }

    // 查看用户详情
    const viewUserProfile = (user) => {
      // 这里可以跳转到用户详情页面
      ElMessage.info(`查看用户 ${user.nickname} 的详情`)
    }

    // 工具函数
    const getStatusType = (status) => {
      const statusMap = {
        'open': 'success',
        'closed': 'info',
        'cancelled': 'danger',
        'finished': 'warning'
      }
      return statusMap[status] || 'info'
    }

    const getStatusText = (status) => {
      const statusMap = {
        'open': '开放中',
        'closed': '已关闭',
        'cancelled': '已取消',
        'finished': '已结束'
      }
      return statusMap[status] || '未知'
    }

    const getActivityTypeText = (type) => {
      const typeMap = {
        'sports': '体育运动',
        'social': '社交活动',
        'learning': '学习交流',
        'other': '其他'
      }
      return typeMap[type] || '未分类'
    }

    const getParticipantPercentage = () => {
      if (!activity.value || !activity.value.max_participants) return 0
      const current = activity.value.participant_count || 0
      return Math.min(Math.round((current / activity.value.max_participants) * 100), 100)
    }

    const getProgressStatus = () => {
      const percentage = getParticipantPercentage()
      if (percentage >= 100) return 'success'
      if (percentage >= 80) return 'warning'
      return undefined
    }

    // 初始化
    onMounted(() => {
      fetchActivityDetail()
    })

    return {
      loading,
      activity,
      participants,
      fetchActivityDetail,
      goBack,
      editActivity,
      deleteActivity,
      viewUserProfile,
      getStatusType,
      getStatusText,
      getActivityTypeText,
      getParticipantPercentage,
      getProgressStatus,
      formatDateTime
    }
  }
}
</script>

<style scoped>
.activity-detail {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 15px;
}

.title-section h1 {
  margin: 0;
  font-size: 24px;
  color: #303133;
}

.title-section p {
  margin: 5px 0 0 0;
  color: #606266;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.loading-container {
  padding: 40px;
}

.activity-content {
  margin-bottom: 20px;
}

.info-card,
.organizer-card,
.stats-card,
.images-card,
.participants-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-title {
  font-size: 16px;
  font-weight: bold;
  color: #303133;
}

.participant-count {
  color: #909399;
  font-size: 14px;
}

.activity-info .info-row {
  display: flex;
  margin-bottom: 15px;
  align-items: flex-start;
}

.activity-info .info-row label {
  min-width: 100px;
  color: #606266;
  font-weight: 500;
}

.activity-info .info-row .value {
  flex: 1;
  color: #303133;
}

.activity-info .info-row .value.description {
  white-space: pre-wrap;
  line-height: 1.6;
}

.tag-item {
  margin-right: 8px;
}

.setting-tag {
  margin-right: 8px;
}

.fee {
  margin-left: 8px;
  font-weight: bold;
  color: #f56c6c;
}

.text-muted {
  color: #c0c4cc;
}

.organizer-info {
  display: flex;
  align-items: center;
  gap: 15px;
}

.organizer-details h3 {
  margin: 0 0 5px 0;
  color: #303133;
}

.organizer-details p {
  margin: 2px 0;
  color: #606266;
  display: flex;
  align-items: center;
  gap: 5px;
}

.stats-content {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
  margin-bottom: 20px;
}

.stat-item {
  text-align: center;
}

.stat-number {
  font-size: 24px;
  font-weight: bold;
  color: #409eff;
}

.stat-label {
  color: #606266;
  font-size: 12px;
  margin-top: 5px;
}

.progress-section {
  margin-top: 20px;
}

.progress-label {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
  font-size: 14px;
  color: #606266;
}

.activity-images {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(100px, 1fr));
  gap: 10px;
}

.activity-image {
  width: 100%;
  height: 100px;
  border-radius: 6px;
}

.empty-participants {
  text-align: center;
  padding: 40px 0;
}

.error-container {
  padding: 40px;
  text-align: center;
}

:deep(.el-card__header) {
  padding: 15px 20px;
  border-bottom: 1px solid #ebeef5;
}

:deep(.el-table) {
  font-size: 14px;
}
</style> 